<!--
 * @Author: 冯本桥
 * @Date: 2025-02-15 18:40:49
 * @LastEditTime: 2025-04-16 15:17:57
 * @LastEditors: 冯本桥
 * @Description: 添加教师
 * @FilePath: \teach_system_fe\src\views\teacherManagement\component\addTeacher.vue
-->
<template>
  <div v-loading="loading">
    <el-breadcrumb>
      <el-breadcrumb-item
        :to="{ path: '/teacherManagement/teacherFile' }"
      >教师管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ titleMessage }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="box-card">
      <div class="user-message">
        <div class="title-box">基本信息</div>
        <div style="padding: 0 0 17px 0; border-bottom: 1px solid #ebebee">
          <from-page
            ref="addFromRef"
            :rules="fromConfig.addTeacherRules"
            :from-config="fromConfig.addTeacher"
            :grid-data="gridData"
            :but-show="false"
            :label-width="null"
            :disabled-from="disabledFrom"
            @submitForm="submitForm"
          />
        </div>
      </div>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        class="demo-ruleForm"
        :disabled="disabledFrom"
      >
        <!-- 教育信息 -->
        <div class="user-message" style="border-bottom: 1px solid #ebebee">
          <!-- 教育信息 -->
          <div class="title-box">教育信息</div>
          <div class="item-box">
            <div
              v-for="(staffChildPOList1, index) in ruleForm.staffChildPOList1"
              :key="index"
              class="grid-item"
            >
              <el-form-item
                label="毕业院校"
                :prop="'staffChildPOList1.' + index + '.almaMater'"
                :rules="{
                  required: true,
                  message: '请输入毕业院校',
                  trigger: 'blur',
                }"
              >
                <el-input
                  v-model="staffChildPOList1.almaMater"
                  placeholder="请输入"
                />
              </el-form-item>

              <el-form-item
                label="学历层次"
                :prop="'staffChildPOList1.' + index + '.educationalLevel'"
                :rules="{
                  required: true,
                  message: '请选择学历层次',
                  trigger: 'change',
                }"
              >
                <el-select
                  v-model="staffChildPOList1.educationalLevel"
                  style="width: 100%"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(i, index2) in schoolList"
                    :key="index2"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item
                label="所学专业"
                :prop="'staffChildPOList1.' + index + '.major'"
                :rules="{
                  required: true,
                  message: '请输入所学专业',
                  trigger: 'blur',
                }"
              >
                <el-input
                  v-model="staffChildPOList1.major"
                  placeholder="请输入"
                />
              </el-form-item>
              <div class="delete-school">
                <el-button
                  v-if="
                    ruleForm.staffChildPOList1.length >= 2 && index + 1 >= 2
                  "
                  type="text"
                  @click="deleteSchool(index, 'staffChildPOList1')"
                >删除</el-button>
              </div>
            </div>
            <div class="add-school">
              <el-image
                style="width: 30px; height: 30px"
                :src="require('@/assets/add-icon.png')"
                fit="fit"
                @click="addInput('staffChildPOList1')"
              />
            </div>
            <el-form-item label="学历证书" prop="certificate">
              <el-upload
                action="/api/system/upload"
                list-type="picture-card"
                multiple
                :file-list="certificate"
                :on-remove="
                  (file, fileList) =>
                    handleRemove(file, fileList, 'certificate')
                "
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(response, file, fileList, 'certificate')
                "
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
          </div>

          <!-- 从业证书 -->
          <div class="item-box">
            <div
              v-for="(staffChildPOList2, index) in ruleForm.staffChildPOList2"
              :key="index"
              class="grid-item"
            >
              <el-form-item
                label="从业证书"
                :prop="'staffChildPOList2.' + index + '.workingCertificate'"
              >
                <el-select
                  v-model="staffChildPOList2.workingCertificate"
                  style="width: 100%"
                  clearable
                  placeholder="请选择从业证书"
                >
                  <el-option
                    v-for="(i, index2) in fromConfig.certificate"
                    :key="index2"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item
                label="获证时间"
                :prop="'staffChildPOList2.' + index + '.certificationTime'"
              >
                <el-date-picker
                  v-model="staffChildPOList2.certificationTime"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择获证时间"
                />
              </el-form-item>

              <el-form-item
                label="过期时间"
                :prop="'staffChildPOList2.' + index + '.expirationTime'"
              >
                <el-date-picker
                  v-model="staffChildPOList2.expirationTime"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择过期时间"
                />
              </el-form-item>
              <el-form-item label="" prop="certificateEmployment">
                <el-upload
                  action="/api/system/upload"
                  list-type="picture-card"
                  multiple
                  :file-list="getValue(staffChildPOList2.certificateEmployment)"
                  :on-remove="
                    (file, fileList) =>
                      handleRemoves(file, fileList, staffChildPOList2)
                  "
                  :on-success="
                    (response, file, fileList) =>
                      handleAvatarSuccessList(
                        response,
                        file,
                        fileList,
                        staffChildPOList2
                      )
                  "
                >
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
              <div class="delete-school">
                <el-button
                  v-if="
                    ruleForm.staffChildPOList2.length >= 2 && index + 1 >= 2
                  "
                  type="text"
                  @click="deleteSchool(index, 'staffChildPOList2')"
                >删除</el-button>
              </div>
            </div>
            <div class="add-school">
              <el-image
                style="width: 30px; height: 30px"
                :src="require('@/assets/add-icon.png')"
                fit="fit"
                @click="addInput('staffChildPOList2')"
              />
            </div>
            <!-- <el-form-item label="" prop="certificate">
              <el-upload
                action="/api/system/upload"
                list-type="picture-card"
                multiple
                :file-list="certificateEmployment"
                :on-remove="
                  (file, fileList) =>
                    handleRemove(file, fileList, 'certificateEmployment')
                "
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(
                      response,
                      file,
                      fileList,
                      'certificateEmployment'
                    )
                "
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item> -->
          </div>
        </div>
        <!-- 工作履历 -->
        <div class="user-message" style="border-bottom: 1px solid #ebebee">
          <div class="title-box">工作履历</div>

          <div class="item-box">
            <div
              v-for="(staffChildPOList3, index) in ruleForm.staffChildPOList3"
              :key="index"
              class="grid-item"
            >
              <el-form-item
                label="工作单位名称"
                :prop="'staffChildPOList3.' + index + '.almaMater'"
              >
                <el-input
                  v-model="staffChildPOList3.almaMater"
                  placeholder="请输入"
                />
              </el-form-item>
              <el-form-item
                label="工作起止时间"
                :prop="'staffChildPOList3.' + index + '.startStopTime'"
              >
                <el-date-picker
                  v-model="staffChildPOList3.startStopTime"
                  style="width: 100%"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                />
              </el-form-item>
              <el-form-item
                label="岗位名称"
                :prop="'staffChildPOList3.' + index + '.major'"
              >
                <el-input
                  v-model="staffChildPOList3.major"
                  placeholder="请输入"
                />
              </el-form-item>
              <div class="delete-school">
                <el-button
                  v-if="
                    ruleForm.staffChildPOList3.length >= 2 && index + 1 >= 2
                  "
                  type="text"
                  @click="deleteSchool(index, 'staffChildPOList3')"
                >删除</el-button>
              </div>
            </div>

            <div class="add-school" style="">
              <el-image
                style="width: 30px; height: 30px"
                :src="require('@/assets/add-icon.png')"
                fit="fit"
                @click="addInput('staffChildPOList3')"
              />
            </div>
          </div>
        </div>

        <!-- 工作信息 -->
        <div class="user-message">
          <div class="title-box">工作信息</div>

          <div class="item-box">
            <div
              v-for="(staffChildPOList4, index) in ruleForm.staffChildPOList4"
              :key="index"
              class="grid-item"
            >
              <el-form-item
                label="所属班级"
                :prop="'staffChildPOList4.' + index + '.classesId'"
              >
                <el-select
                  v-model="staffChildPOList4.classesId"
                  style="width: 100%"
                  clearable
                  placeholder="请选择所属班级"
                >
                  <el-option
                    v-for="(i, index2) in classesOption"
                    :key="index2"
                    :label="i.name"
                    :value="i.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="担任岗位"
                :prop="'staffChildPOList4.' + index + '.positionHeld'"
                :rules="{
                  required: true,
                  message: '请选择担任岗位',
                  trigger: 'blur',
                }"
              >
                <el-select
                  v-model="staffChildPOList4.positionHeld"
                  style="width: 100%"
                  clearable
                  placeholder="请选择担任岗位"
                >
                  <el-option
                    v-for="(i, index2) in positionHeldOption"
                    :key="index2"
                    :label="i.roleName"
                    :value="i.roleId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="人员类型">
                <el-select
                  v-if="
                    staffChildPOList4.positionHeld ===
                      'e0c52ba1009c404587896521c54f0d03'
                  "
                  v-model="staffChildPOList4.staffType"
                  style="width: 100%"
                  clearable
                  placeholder="请选择人员类型"
                >
                  <el-option
                    v-for="(i, index2) in personTypeList1"
                    :key="index2"
                    :label="i.name"
                    :value="i.id"
                  />
                </el-select>
                <el-select
                  v-else
                  v-model="staffChildPOList4.staffType"
                  style="width: 100%"
                  clearable
                  placeholder="请选择人员类型"
                >
                  <el-option
                    v-for="(i, index2) in personTypeList"
                    :key="index2"
                    :label="i.name"
                    :value="i.id"
                  />
                </el-select>
              </el-form-item>
              <div class="delete-school">
                <el-button
                  v-if="
                    ruleForm.staffChildPOList4.length >= 2 && index + 1 >= 2
                  "
                  type="text"
                  @click="deleteSchool(index, 'staffChildPOList4')"
                >删除</el-button>
              </div>
            </div>

            <div class="add-school">
              <el-image
                style="width: 30px; height: 30px"
                :src="require('@/assets/add-icon.png')"
                fit="fit"
                @click="addInput('staffChildPOList4')"
              />
            </div>
            <el-form-item label="附件信息">
              <el-upload
                class="upload-demo"
                action="/api/system/upload"
                multiple
                :file-list="file"
                :on-remove="
                  (file, fileList) => handleRemove(file, fileList, 'file')
                "
                :on-success="
                  (response, file, fileList) =>
                    handleAvatarSuccess(response, file, fileList, 'file')
                "
                :on-preview="(file) => fileOpen(file)"
              >
                <div class="box-uoload-item">
                  <i class="el-icon-plus" style="font-size: 20px" />
                </div>
                <div slot="tip" class="el-upload__tip">
                  可上传教师个人简历、工作合同等信息
                </div>
              </el-upload>
            </el-form-item>
          </div>
        </div>

        <!-- 确定 -->
        <div v-if="!disabledFrom" class="user-message box-card submit-btn">
          <el-button
            style="padding: 15px 40px"
            type="primary"
            @click="submit"
          >确定</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as fromConfig from '../config'
import FromPage from '@/components/Basic/FromPage/index'
import { getRoleTypes, getList } from '../api/index'
import { submitStaff, getDetailById } from '../api/teacher'
export default {
  components: {
    FromPage
  },
  data () {
    return {
      personTypeValue: '',
      fromConfig: fromConfig,
      titleMessage: '添加教师',
      gridData: {
        columns: 3, // 默认列数
        rows: 3, // 默认行数
        rowsWidth: '10', // 默认行高
        columnsNumber: '15px', // 默认列宽
        rowsNumber: '95px' // 默认行间距
      },
      loading: false,
      imageUrl: '',
      ruleForm: {
        staffId: '',
        certificateEmployment: '',
        file: '',
        certificate: '',
        ...fromConfig.addFromValue()
      },
      idS: '',
      positionHeldOption: [],
      classesOption: [],
      personTypeList1: [
        {
          name: '保安',
          id: 6
        },
        {
          name: '炊事',
          id: 8
        }
      ],
      personTypeList: [
        {
          name: '保育师',
          id: 1
        },
        {
          name: '托育师',
          id: 2
        },
        {
          name: '育婴员',
          id: 3
        },
        {
          name: '幼儿照护师',
          id: 4
        },
        {
          name: '幼儿教师',
          id: 5
        },
        {
          name: '保安',
          id: 6
        },
        {
          name: '卫生保健',
          id: 7
        },
        {
          name: '炊事',
          id: 8
        }
      ],
      schoolList: this.$store.getters.dict.educations,
      disabledFrom: false,

      certificate: [], // 学历回显
      certificateEmployment: [], // 从业回显
      file: [], // 附件回显
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  computed: {
    ...mapGetters(['curArea']),

    getValue () {
      return (value) => {
        return value
          ?.split(',')
          .filter((url) => url.trim() !== '')
          .map((url) => ({ url: url.trim() }))
      }
    }
  },
  created () {
    const { types, id } = this.$route.query
    if (types === 'edit') {
      this.titleMessage = '教师编辑'
      this.idS = id
      this.getInfoList()
    }
    this.getRole()
    this.getUser()
  },
  mounted () {},
  beforeDestroy () {
    this.$refs.ruleForm.resetFields()
  },
  methods: {
    async getInfoList () {
      this.loading = true
      try {
        const res = await getDetailById({ staffId: this.idS })
        this.ruleForm = JSON.parse(JSON.stringify(res))
        this.ruleForm.gender = String(this.ruleForm.gender)
        console.log(this.ruleForm, '----------')

        const a = [
          'staffChildPOList1',
          'staffChildPOList2',
          'staffChildPOList3',
          'staffChildPOList4'
        ]
        a.forEach((element) => {
          if (!this.ruleForm[element] || this.ruleForm[element].length === 0) {
            this.ruleForm[element] = fromConfig.addFromValue()[element]
          }
        })

        const parseUrls = (urls) =>
          urls
            ?.split(',')
            .filter((url) => url.trim() !== '')
            .map((url) => ({ url: url.trim() })) || []

        this.certificate = parseUrls(this.ruleForm.certificate)
        this.certificateEmployment = parseUrls(
          this.ruleForm.certificateEmployment
        )
        this.file = parseUrls(this.ruleForm.file).map((file) => ({
          ...file,
          name: file.url
        }))
        this.$nextTick(() => {
          this.$refs.addFromRef.formDate = this.ruleForm
        })
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    handleAvatarSuccess (response, file, fileList, key) {
      const a = []
      fileList.forEach((element) => {
        if (
          element.response &&
          element.response?.data &&
          element.response?.data.url
        ) {
          a.push(element.response.data.url)
        }
      })
      console.log(a)

      this.ruleForm[key] =
        this.ruleForm[key] && this.ruleForm[key].trim() !== ''
          ? this.ruleForm[key] + ',' + a.join(',')
          : a.join(',')
    },
    handleAvatarSuccessList (response, file, fileList, key) {
      const urls = fileList
        .map((element) => {
          if (
            element.response &&
            element.response.data &&
            element.response.data.url
          ) {
            return element.response.data.url
          }
          return element.url
        })
        .filter(Boolean)

      // 确保 key.certificateEmployment 是字符串
      const existingUrls = key.certificateEmployment
        ? key.certificateEmployment
          .split(',')
          .filter((url) => url.trim() !== '')
        : []

      // 合并新上传的文件 URL，并去重
      const mergedUrls = [...new Set([...existingUrls, ...urls])]

      // 将结果存储为逗号分隔的字符串
      key.certificateEmployment = mergedUrls.join(',')

      console.log(key.certificateEmployment, '上传成功后的数据')
    },

    fileOpen (file) {
      console.log(file)
    },

    handleRemove (file, fileList, key) {
      if (!fileList.length) {
        this.ruleForm[key] = ''
        console.log(this.ruleForm[key], 'aa')
        return
      }
      const a = []
      fileList.forEach((element) => {
        if (element.url) {
          a.push(element.url)
        }
      })
      console.log(a, '删除')
      this.ruleForm[key] = a.join(',')
    },

    handleRemoves (file, fileList, key) {
      // 获取剩余的文件 URL
      const remainingUrls = fileList
        .map((element) => element.url)
        .filter(Boolean)

      // 确保 key.certificateEmployment 是字符串
      const existingUrls = key.certificateEmployment
        ? key.certificateEmployment
          .split(',')
          .filter((url) => url.trim() !== '')
        : []

      // 更新 certificateEmployment，移除被删除的文件
      const updatedUrls = existingUrls.filter((url) =>
        remainingUrls.includes(url)
      )

      // 将结果存储为逗号分隔的字符串
      key.certificateEmployment = updatedUrls.join(',')

      console.log(key.certificateEmployment, '删除后的数据')
    },

    submitForm (value) {
      if (value !== '') {
        this.$refs.ruleForm.validate((valid) => {
          console.log(value)
          if (valid) {
            const b = {}
            for (let i = 0; i < fromConfig.addTeacher.length; i++) {
              const key = fromConfig.addTeacher[i]['value']
              const valueToAssign = value[key]

              // 只在valueToAssign不是空值时才赋值
              if (valueToAssign !== undefined && valueToAssign !== '') {
                b[key] = valueToAssign
              }
            }
            b.gender = Number(b.gender)
            b.age = Number(b.age)

            const list = JSON.parse(JSON.stringify(this.ruleForm))
            list.id ? (list.staffId = list.id) : ''

            this.addTeacher(Object.assign({}, list, b))
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },

    submit () {
      this.$nextTick(() => {
        this.$refs.addFromRef.submitForm()
      })
    },

    addInput (key) {
      const arr = fromConfig.addFromValue()

      this.ruleForm[key].push(arr[key][0])
    },

    deleteSchool (index, key) {
      this.ruleForm[key].splice(index, 1)
    },

    async getRole () {
      try {
        const res = await getRoleTypes()
        this.positionHeldOption = res
      } catch (error) {
        console.log(error)
      }
    },

    async getUser () {
      try {
        const res = await getList({
          areaId: this.curArea.areaId || '',
          pageNum: 0,
          pageSize: 10
        })
        this.classesOption = res.content
      } catch (error) {
        console.log(error)
      }
    },

    async addTeacher (value) {
      console.log(value)

      this.loading = true
      try {
        await submitStaff(value)
        if (this.titleMessage === '教师编辑') {
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
        } else {
          this.$message({
            type: 'success',
            message: '新增成功'
          })
        }

        this.$refs.ruleForm.resetFields()
        this.$router.push({ path: '/teacherManagement/teacherFile' })
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  padding: 10px 30px;
  background-color: white;
  margin-top: 20px;
}

.submit-btn {
  margin-bottom: 30px;
  text-align: center;
  border-top: 1px solid #ebebee;
  padding: 20px 0;
}

.title-box {
  margin-bottom: 30px;
  font-weight: bold;
  font-size: 20px;
}

.grid-item {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  // grid-template-rows: repeat(3, 10px);
  gap: 15px 95px;
  width: 93%;
  // margin-bottom: 30px;
  position: relative;
}

.user-message {
  margin-top: 30px;
}

.item-box {
  position: relative;
}

.add-school {
  position: absolute;
  top: 38px;
  right: 30px;
}

.delete-school {
  position: absolute;
  top: 38px;
  right: -50px;
}
.demo-ruleForm {
  ::v-deep .el-form-item__label {
    font-weight: bold !important;
  }
}

.box-uoload-item {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  cursor: pointer;
}
</style>
